package service

import (
	"context"
	"errors"

	"gomain/app/model"

	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gvalid"
)

type UserService struct{}

var User = &UserService{}

func (s *UserService) Login(username, password string) (*model.User, error) {
	ctx := context.Background()

	// 添加日志
	g.Log().Info(ctx, "用户尝试登录", "username", username)

	if e := gvalid.New().Data(g.Map{
		"username": username,
		"password": password,
	}).Rules(g.Map{
		"username": "required",
		"password": "required",
	}).Run(ctx); e != nil {
		g.Log().Error(ctx, "登录参数验证失败", "error", e.Error())
		return nil, e
	}

	password = gmd5.MustEncrypt(password)

	var user *model.User
	err := g.Model("users").
		Where("username", username).
		Where("password", password).
		Scan(&user)
	if err != nil {
		g.Log().Error(ctx, "数据库查询失败", "error", err.Error())
		return nil, err
	}

	if user == nil || user.Id == 0 {
		g.Log().Warning(ctx, "登录失败：用户名或密码错误", "username", username)
		return nil, errors.New("用户名或密码错误")
	}
	g.Log().Info(ctx, "用户登录成功", "userId", user.Id, "username", username)
	return user, nil
}

// 获取用户角色
func (s *UserService) GetUserRoles(userId int) ([]model.Role, error) {
	var roles []model.Role
	err := g.Model("user_roles ur").
		InnerJoin("roles r", "ur.role_id=r.id").
		Fields("r.*").
		Where("ur.user_id", userId).
		Where("r.status", 1).
		Scan(&roles)
	return roles, err
}

// 检查用户权限
func (s *UserService) CheckPermission(userId int, permission string) (bool, error) {
	// 特殊处理：userId=1 拥有所有权限
	if userId == 1 {
		return true, nil
	}

	count, err := g.Model("user_roles ur").
		InnerJoin("role_permissions rp", "ur.role_id=rp.role_id").
		InnerJoin("permissions p", "rp.permission_id=p.id").
		Where("ur.user_id", userId).
		Where("p.code", permission).
		Where("p.status", 1).
		Count()
	return count > 0, err
}
